import React, { useState, useEffect } from 'react';
import BreadCrumb from '@/components/BreadCrumb';
import { SystemRoute, modifySysConfig } from '~/API/index';
import recursionForm from '@/common/recursionForm';

import s from './style.module.css';
import { Table, Button, Confirm, Form, Input, Loading, Message, Dialog, Select } from '@knownsec/react-component';
// import SelectAnt from '@/components/SelectAnt';

export default function email() {
  const [refe, setRef] = useState(false);
  const [loading, setLoading] = useState(false);
  const [showDia, setShowd] = useState(false);
  const [dataList, setData] = useState([]);
  const [netList, setNet] = useState([]);
  const [selTable, setSelTable] = useState([]);
  const createForm = React.useRef();
  const columns = [
    {
      title: '扫描网口',
      dataIndex: 'name',
      render:(e)=>{return e||'--'}
    },
    {
      title: '目标IP地址',
      dataIndex: 'to',
      render:(e)=>{return e||'--'}
    },
    {
      title: '子网掩码/前缀',
      dataIndex: 'netmask',
      render:(e)=>{return e||'--'}
    },
    {
      title: '网关地址',
      dataIndex: 'via',
      render:(e)=>{return e||'--'}
    },
    {
      title: '操作',
      dataIndex: 'option',
      render: (e, row) => {
        return (
          <span
            className={s.operation}
            onClick={() => {
              delDia([row]);
            }}
          >
            删除
          </span>
        );
      },
    },
  ];
  const delBatch = () => {
    const delList = selTable.map((i) => {
      return dataList[i];
    });
    delDia(delList);
  };
  const delDia = (list) => {
    Confirm({
      title: '确认提示',
      pro: true,
      message: <div className={s.confirmbox}>确认要删除选择的路由吗？</div>,
      onconfirm: async () => {
        const res = await SystemRoute('DELETE', { route_list: list });
        if (res.status === 'success') {
          Message.show({
            pro: true,
            type: 'success',
            message: '删除路由成功',
            showClose: false,
          });
          getRoutes();
        }
      },
    });
  };
  const onValues = (data, allv) => {
    const values = recursionForm(data);
    if (data.name) {
      const n = data.name.split('|%|');
      values.name = n[0];
      values.type = n[1];
    }
    createForm.current.setFieldsValue(values);
  };
  const showDialog = (row = {}) => {
    console.log(createForm);
    createForm.current.resetFields();
    setShowd(true);
  };
  const onconfirmv = async () => {
    try {
      const flag = await createForm.current.validateFields(['name', 'to', 'netmask', 'via']);
      if (flag) {
        const sd = createForm.current.getFieldValue();
        const obj = Object.assign({}, sd);
        obj.name = obj.name[0].split('|%|')[0]
        setLoading(true);
        SystemRoute('POST', obj)
          .then((res) => {
            setLoading(false);
            if (res.status === 'success') {
              getRoutes();
              Message.show({
                pro: true,
                type: 'success',
                message: '添加成功',
                showClose: false,
              });
            }
            setShowd(false);
          })
          .catch((err) => {
            setLoading(false);
            const emsg = Object.values(err.data)[0][0] || '添加失败';
            Message.show({
              pro: true,
              type: 'error',
              message: emsg,
              showClose: false,
            });
          });
      }
    } catch (errorInfo) {
      return false;
    }
  };
  const getRoutes = () => {
    setLoading(true);
    SystemRoute('GET').then((res) => {
      setLoading(false);
      if (res.status == 'success') {
        const data = res.data || [];
        data.map((item, index) => (item.id = Math.random().toString(36).slice(-6) + index));
        setData(data);
        setSelTable([]);
        setRef(!refe);
      }
    });
  };
  const getConfigData = () => {
    modifySysConfig('GET').then((res) => {
      if (res.status === 'success') {
        const ports = res.data.ports.map((item) => {
          const r = { label: item.name, value: item.name + '|%|' + item.type };
          return r;
        });
        setNet(ports);
      }
    });
  };
  useEffect(() => {
    getRoutes();
    getConfigData();
  }, []);
  return (
    <>
      <BreadCrumb
        arr={[
          { link: '', name: '网络配置' },
          { link: '', name: '路由配置', active: true },
        ]}
      />
      <div className={s.routerMain}>
        {/* <Loading show={loading} /> */}
        <div className={s.tableBox}>
          <div className={s.tool}>
            <Button
              pro
              type="primary"
              onClick={() => {
                showDialog(false);
              }}
            >
              添加
            </Button>
          </div>
          <div>
            <Button
              pro
              type="text"
              className="delete-btn p0"
              disabled={!selTable.length}
              onClick={() => {
                delBatch();
              }}
            >
              批量删除
            </Button>
          </div>
          <Table
            selectable
            refre={refe}
            tableLoading={loading}
            loadingLabel=""
            columns={columns}
            className={selTable.length ? 'half-select' : ''}
            data={dataList}
            getCheckedList={(e) => {
              setSelTable(e);
            }}
          ></Table>
        </div>
      </div>
      <Dialog
        leftTitle={true}
        pro={true}
        visible={showDia}
        className={s.dialogName}
        title="添加路由"
        confirmText=""
        cancelText=""
        onhide={() => setShowd(false)}
      >
        <div className={s.inpNameBox}>
          <Form
            ref={createForm}
            onValuesChange={(newItem, allValues) => {
              const values = Object.keys(newItem).reduce((total, key) => {
                let value
                if (newItem[key].selectedItem) {
                  if (newItem[key].selectedItem.length > 0) {
                    value = [newItem[key].selectedItem[0].value]
                  } else if (newItem[key].selectedItem.length === 0) {
                    value = item[key]
                  }
                } else if (Object.keys(newItem[key]).indexOf('value') > -1) {
                  value = newItem[key].value
                } else {
                  value = newItem[key]
                }
                total[key] = value
                return total
              }, {})
              if (values?.name?.length) {
                const n = values.name[0].split('|%|');
                // values.name = n[0];
                values.type = n[1];
              }
              console.log(values)
              createForm.current.setFieldsValue(values);
              // onValues(newItem, allValues);
            }}
          >
            <Form.Item
              rules={[{ required: true, message: '请选择扫描网口' }]}
              name="name"
              label="扫描网口"
              initialValue={['']}
            >
              <Select pro option={netList} placeholder="请选择扫描网口" className={s.inpName} />
            </Form.Item>
            {/* <Form.Item
              rules={[{ required: true, validator: validatormap }]}
              name="is_periodic"
              label="网络类型"
            >
              <Radio.Group className={s.radioBorder}>
                <Radio value={true} className={s.radio0}>
                  IPv4
                </Radio>
                <Radio value={false} className={s.radio0}>
                  IPv6
                </Radio>
              </Radio.Group>
            </Form.Item> */}
            <Form.Item
              rules={[{ required: true, message: '请输入目标IP地址' }]}
              name="to"
              label="目标IP地址"
              valuePropName="value"
            >
              <Input
                pro
                className={s.inpName}
                maxlength={50}
                placeholder="请输入IPv4或IPv6地址"
              ></Input>
            </Form.Item>
            <Form.Item
              rules={[{ required: true, message: '请输入子网掩码/前缀' }]}
              name="netmask"
              label="子网掩码/前缀"
            >
              <Input
                pro
                className={s.inpName}
                maxlength={50}
                placeholder="请输入IPv4地址的子网掩码或IPv6地址的前缀长度"
              ></Input>
            </Form.Item>
            <Form.Item
              rules={[{ required: true, message: '请输入网关地址' }]}
              name="via"
              label="网关地址"
            >
              <Input pro className={s.inpName} maxlength={50} placeholder="请输入网关地址"></Input>
            </Form.Item>
          </Form>
          <div className={s.diafooter}>
            <Button
              pro
              type="default"
              style={{ marginRight: 20 }}
              onClick={() => {
                setShowd(false);
              }}
            >
              取消
            </Button>
            <Button
              pro
              type="primary"
              onClick={() => {
                onconfirmv();
              }}
            >
              确认
            </Button>
          </div>
        </div>
      </Dialog>
    </>
  );
}
